<template>
  <!-- 执行案件反馈处理页面 -->
  <div
    v-loading="loadingState.isDetail"
    class="wrapper"
  >
    <div class="title">
      执行案件反馈
    </div>
    <title-name :title="processName + '-' + taskName" />
    <a-card
      :body-style="{ padding: '24px 32px' }"
      :bordered="false"
    >
      <template>
        <title-name title="节点信息" />
        <slot name="extraResult" />
        <a-descriptions
          class="mb20"
          title=""
        >
          <a-descriptions-item label="提示内容">
            {{ currentCommit.postilSuggestion || '' }}
          </a-descriptions-item>
          <a-descriptions-item label="反馈人员">
            {{ currentCommit.userName || '' }}
          </a-descriptions-item>
          <a-descriptions-item label="反馈时间">
            {{ currentTime }}
          </a-descriptions-item>
        </a-descriptions>
      </template>

      <slot name="extraOption" />

      <template>
        <title-name title="附件" />
        <a-form
          ref="form1"
          :form="form"
        >
          <a-form-item class="approval-item">
            <b-upload
              business-code="LCM10"
              upload-type="single"
              :file-list.sync="formInfo.feedbackFileList"
            />
          </a-form-item>
        </a-form>
        <title-name title="反馈意见" />
        <a-form
          ref="form1"
          :form="form"
        >
          <a-form-item class="approval-item">
            <BaseTextarea
              v-model="formInfo.feedbackSuggestion"
              placeholder="请填写反馈意见"
            />
          </a-form-item>
          <slot name="extraMiddle" />
          <div class="overfloat">
            <div class="floatRight">
              <a-button
                style="margin-right: 20px"
                @click="handleClose"
              >
                关闭
              </a-button>
              <a-button
                v-if="buttonConfig.ok.isShow"
                :loading="loading"
                type="primary"
                @click="handelApproval"
              >
                保存
              </a-button>
            </div>
          </div>
        </a-form>
      </template>
    </a-card>
    <a-card>
      <title-name title="项目信息" />
      <a-descriptions :column="{ xs: 3, sm: 3, md: 3 }">
<!--        <a-descriptions-item label="分公司名称">-->
<!--          {{ (formInfo.projectInfo && formInfo.projectInfo.branchComName) || '无' }}-->
<!--        </a-descriptions-item>-->
<!--        <a-descriptions-item label="项目名称">-->
<!--          {{ (formInfo.projectInfo && formInfo.projectInfo.projectName) || '无' }}-->
<!--        </a-descriptions-item>-->
        <a-descriptions-item label="所属单位">
          {{ formInfo.projectInfo.branchComName+'/'+formInfo.projectInfo.projectName || '无' }}</a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card>
      <title-name title="执行案件信息" />
      <div class="main_content">
        <a-descriptions :column="{ xs: 3, sm: 3, md: 3 }">
          <a-descriptions-item label="函件编号">
            {{ formInfo.code || '无' }}
          </a-descriptions-item>
          <a-descriptions-item label="函件名称">
            {{ formInfo.name || '无' }}
          </a-descriptions-item>
          <a-descriptions-item label="发函单位">
            {{ formInfo.seddingUnit || '无' }}
          </a-descriptions-item>
        </a-descriptions>
        <a-descriptions :column="{ xs: 3, sm: 3, md: 3 }">
          <a-descriptions-item label="申请执行人">
            {{ formInfo.executor || '无' }}
          </a-descriptions-item>
          <a-descriptions-item label="被执行人">
            {{ formInfo.byExecutor || '无' }}
          </a-descriptions-item>
          <a-descriptions-item label="收到时间">
            {{ formInfo.receivedDate || '无' }}
          </a-descriptions-item>
        </a-descriptions>
        <a-descriptions :column="{ xs: 3, sm: 3, md: 3 }">
          <a-descriptions-item label="处理状态">
            {{ resolveStatus(formInfo.caseStatus) || '无' }}
          </a-descriptions-item>
        </a-descriptions>
        <a-descriptions :column="{ xs: 3, sm: 3, md: 3 }">
          <a-descriptions-item label="备注">
            {{ formInfo.remark || '无' }}
          </a-descriptions-item>
        </a-descriptions>
        <a-descriptions :column="{ xs: 3, sm: 3, md: 3 }">
          <a-descriptions-item label="主要内容">
            {{ formInfo.content || '无' }}
          </a-descriptions-item>
        </a-descriptions>
        <a-descriptions :column="{ xs: 3, sm: 3, md: 3 }">
          <a-descriptions-item label="创建人">
            {{ formInfo.creatorName || '无' }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formInfo.createTime || '无' }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
  </div>
</template>

<script>
import { getProcessNodeList, completeTask } from '@/api/process'
import { getOrgEmployeesListBy } from '@/api/commons'
import moment from 'moment'
import Vue from 'vue'
import { notifyParentWindow } from '@/utils/util.js'
import riskListApi from '@/api/legal/risk/list'
import { editByComments, findBaseByCommentsId, findListByComments } from '@/api/legal'
import { getCommentDetailByApproval, editComment } from '@/api/legal/caseAndLetter/caseManage.js'
import { CASE_STATUS_MAP } from '@/config/businessConfig.js'

const columnApprove = [
  {
    title: '序号',
    width: 80,
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '审批人',
    dataIndex: 'userName',
    ellipsis: true,
    width: 180
  },
  {
    title: '审批时间',
    dataIndex: 'createTime',
    ellipsis: true,
    width: 180
  },
  {
    title: '节点名称',
    dataIndex: 'taskName',
    ellipsis: true,
    width: 180
  },
  {
    title: '滞留时间',
    dataIndex: 'durationInMillis',
    ellipsis: true,
    width: 140
  },
  {
    title: '审批意见',
    dataIndex: 'formData.opinions',
    scopedSlots: { customRender: 'opinions' },
    ellipsis: true
  }
]

export default {
  name: 'Approval',
  props: {
    text: {
      type: String,
      default: ''
    },
    /**
     * 审批时的回调，返回false时，会阻止审批；返回true时，则正常进行后续流程
     * @param {String} flag enum: 'approval' || 'unApproval'   通过 || 不通过
     */
    callbackFn: {
      type: [Function, Object],
      default: null
    },
    /*
     * 提交之后
     * */
    beforeSubmitFn: {
      type: [Function, Object],
      default: null
    },
    submitData: {
      type: Object,
      default() {
        return {}
      }
    },
    buttonConfig: {
      type: Object,
      default() {
        return {
          no: {
            isShow: true,
            title: '审批不通过'
          },
          ok: {
            isShow: true,
            title: '审批通过'
          }
        }
      }
    }
  },
  data() {
    return {
      loadingState: {
        isDetail: false
      },
      formInfo: {
        projectInfo: {
          projectName: "",
          branchComName: ""
        }
      },
      form: {
        orgSelectedName: '',
        orgSelectedLabel: '',
        jobsSelectedName: undefined, //岗位
        respEmployeeId: undefined, //人员,
        fileInfoVO: []
      },
      treeCheckable: true,
      loading: false,

      childrenNode: 'jobs',

      columnApprove,
      opinions: '',
      approveInfos: [], // 审批流程信息
      procInstId: '', //当前流程实例ID
      taskId: '', //当前流程节点ID
      processName: '', //流程名称
      taskName: '', //当前流程节点名称
      taskDefKey: '', //任务标识
      currentTime: '', //当前审批时间
      currentUser: '', //当前审批人
      flowRequesting: false,
      detailUrl: null, //详情地址

      assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
      assignCode: '', //候选组编码 岗位编码
      assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
      businessType: '', //业务类型 0 项目,

      currentCommit: {}
    }
  },
  computed: {},
  created() {
    const {
      type,
      code,
      level,
      btype,
      businessId,
      procInstId,
      name,
      processName,
      detailUrl,
      taskId,
      taskDefKey
    } = this.$route.query
    if (type) {
      this.assignType = type
      this.assignCode = code
      this.assignLevel = level
      this.businessType = btype
    }
    this.id = businessId
    if (!this.id) {
      this.$error({ content: '无指定业务ID，将自动关闭' })
      setTimeout(() => {
        window.close()
      }, 1500)
      return
    }
    this.procInstId = procInstId
    this.taskName = decodeURIComponent(name)
    this.processName = decodeURIComponent(processName)
    document.title = this.processName + '-' + this.taskName
    if (detailUrl) {
      this.detailUrl = decodeURIComponent(detailUrl)
    }
    // else {
    //     this.detailUrl = '/process/auditBusinessDetail'
    // }
    this.taskId = taskId
    this.taskDefKey = taskDefKey
    this.currentTime = moment().format('YYYY-MM-DD HH:mm:ss')
    this.currentUser = Vue.getAcloudProvider().getUserInfo()
    // //获取流程节点执行情况
    // this.getProcessNodes()
    // this.getComments()
    this.getDetailReq()
  },
  mounted() {},
  destroyed() {},
  methods: {
    handleClose() {
      this.$close()
    },
    /**
     * 解析状态值
     */
    resolveStatus(status) {
      return CASE_STATUS_MAP[status] || ''
    },
    async getDetailReq() {
      try {
        if (this.loadingState.isDetail) return
        this.loadingState.isDetail = true
        const params = {
          id: this.$route.query.businessId
        }
        const res = await getCommentDetailByApproval(params)
        this.formInfo = res.data || {}
        this.currentCommit =
          this.formInfo.executionComments.find((item) => item.id === this.$route.query.businessId) || {}
        this.currentCommit = {
          ...this.currentCommit,
          userName: this.$userInfo()?.name
        }
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isDetail = false
    },
    async getComments() {
      let res = await findBaseByCommentsId({ id: this.id })
      if (res.code === this.SUCCESS_CODE) {
        let res1 = await findListByComments({ baseId: res.data.id })
        this.currentCommit = res1.data.find((v) => v.id === this.id) || {}
        console.log(this.currentCommit)
      }
    },
    handleDetail() {
      // const token = Vue.getAcloudProvider().getAccessToken();
      let routeData = this.$router.resolve({
        path: this.detailUrl,
        query: {
          businessId: this.id,
          businessType: this.$route.query.businessType || '',
          id: this.id,
          type: 'approve'
        }
      })
      window.open(routeData.href, '_blank')
    },
    getProcessNodes() {
      this.flowRequesting = true
      getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
        .then((res) => {
          if (res.code === 200) {
            const data = res.data
            const userIds = data.map((d) => {
              if (d.formData) {
                d.formData = JSON.parse(d.formData)
              }
              return d.assignee
            })
            getOrgEmployeesListBy({ userIds }).then((employees) => {
              this.flowRequesting = false
              res.data.forEach((r) => {
                employees.data.some((e) => {
                  if (e.userId === r.assignee) {
                    r.userName = e.name
                    return true
                  }
                })
              })
              this.approveInfos = res.data
            })
          }
        })
        .catch(() => {
          this.flowRequesting = false
        })
    },
    submit(reject) {
      const data = {
        formData: {
          opinions: this.opinions,
          reject,
          projectId: ''
        },
        assignTypeEnum: this.assignType, //指派类型
        assgins: this.form.respEmployeeId, //人员
        groupEnum: this.form.jobsSelectedName, //岗位
        procInstId: this.procInstId,
        taskId: this.taskId,
        userId: this.currentUser.id
      }
      console.log(data)
      const variable = {}
      // return;
      if (reject) {
        variable.reject = true
      }

      data.variables = {
        ...variable,
        ...this.submitData // 特殊流程的数据，转交给审批
      }

      return completeTask(data)
        .then((res) => {
          if (res.status === 200) {
            notifyParentWindow() // 通知父窗口
            // this.$success({
            //   content: '保存成功，即将自动关闭当前窗口',
            //   onOk() {
                window.close()
            //   }
            // })
            // setTimeout(() => {
            //   window.close()
            // }, 2000)
          } else {
            this.$error({ content: '保存失败，请稍后重试' })
          }
          return res
        })
        .catch((err) => {
          return err
        })
    },
    async handelUnApproval() {
      const callbackFn = this.callbackFn
      if (callbackFn && !callbackFn('unApproval')) return

      if (!this.opinions) {
        this.$warning({ content: '请填写反馈意见' })
        return
      }
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批不通过？',
        okType: 'danger',
        onOk: async () => {
          return new Promise((resolve, reject) => {
            this.submit(true)
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel: () => {}
      })
    },

    async handelApproval() {
      try {
        if (!this.formInfo.feedbackSuggestion) {
          return this.$noticeWarning('反馈意见不能为空')
        }
        if (this.loading) return
        this.loading = true
        const params = {
          id: this.$route.query.businessId, // 批注ID
          feedbackFileList:
            (this.formInfo.feedbackFileList && this.formInfo.feedbackFileList.map((item) => item.commonId)) || [],
          feedbackSuggestion: this.formInfo.feedbackSuggestion
        }
        await editComment(params)
        await this.submit(false)
      } catch (e) {
        console.error(e)
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
.wrapper {
  padding: 20px;

  .title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
  }

  /deep/ .approval-item .ant-form-item-control-wrapper {
    width: 100%;
  }
}

.wrapper-row {
  padding-left: 55px;
  font-weight: bold;
  letter-spacing: 1px;
}

/deep/ .ant-form-item label {
  font-size: 12px;
}

/deep/ .ant-btn {
  border-radius: 5px;
}

/deep/ .ant-input {
  /*width: 70%;*/
  border-radius: 5px;
}

/deep/ .ant-card.ant-card-bordered {
  border-radius: 5px;
}

.ant-avatar-lg {
  width: 48px;
  height: 48px;
  line-height: 48px;
}

.list-content-item {
  color: rgba(0, 0, 0, 0.45);
  display: inline-block;
  vertical-align: middle;
  font-size: 14px;
  margin-left: 40px;

  span {
    line-height: 20px;
  }

  p {
    margin-top: 4px;
    margin-bottom: 0;
    line-height: 22px;
  }
}

.title-name {
  border-left: 5px solid #1890ff;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 20px;
  padding-left: 15px;
  height: 20px;
  line-height: 20px;
}

/deep/ .table-page-search-wrapper .ant-form-inline .ant-row .ant-col.ant-col-sm-24.ant-col-md-12 {
  padding-left: 80px;
}

/deep/ .ant-form-item .ant-form-item-control-wrapper {
  /*width: 100%;*/
}

/deep/ .col .ant-form-item .ant-form-item-control-wrapper {
  width: calc(100% - 135px);
}
</style>

